package com.yuexun.beilunpatient.ui.satisfaction.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.BaseEntity;
import com.yuexun.beilunpatient.base.BaseKJActivity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.ui.main.bean.AreaBean;
import com.yuexun.beilunpatient.ui.main.bean.AreaHospBean;
import com.yuexun.beilunpatient.ui.main.model.impl.AreaHospModel;
import com.yuexun.beilunpatient.ui.main.presenter.impl.AreaHospPresenter;
import com.yuexun.beilunpatient.ui.main.ui.view.IAreaHospView;
import com.yuexun.beilunpatient.ui.satisfaction.adapter.SatisfactionTopicAdapter;
import com.yuexun.beilunpatient.ui.satisfaction.bean.SatisfactionAnswerDtlBean;
import com.yuexun.beilunpatient.ui.satisfaction.bean.SatisfactionDtlBean;
import com.yuexun.beilunpatient.ui.satisfaction.bean.TemplateBean;
import com.yuexun.beilunpatient.ui.satisfaction.bean.TemplateTypeBean;
import com.yuexun.beilunpatient.ui.satisfaction.bean.UpdateSatisfactionBean;
import com.yuexun.beilunpatient.ui.satisfaction.model.impl.SatisfactionModel;
import com.yuexun.beilunpatient.ui.satisfaction.presenter.ICreateSatisfactionPresenter;
import com.yuexun.beilunpatient.ui.satisfaction.presenter.impl.CreateSatisfactionPresenter;
import com.yuexun.beilunpatient.ui.satisfaction.presenter.impl.SatisfactionDtlPresenter;
import com.yuexun.beilunpatient.ui.satisfaction.presenter.impl.TemplatePresenter;
import com.yuexun.beilunpatient.ui.satisfaction.ui.view.ICreateSatisfactionView;
import com.yuexun.beilunpatient.ui.satisfaction.ui.view.ISatisfactionDtlView;
import com.yuexun.beilunpatient.ui.satisfaction.ui.view.ITemplateView;
import com.yuexun.beilunpatient.widget.ActionSheetDialog;
import com.yuexun.beilunpatient.widget.FlowLayout;
import com.yuexun.beilunpatient.widget.FlowRadioGroup;
import com.yuexun.beilunpatient.widget.LinearLayoutForListView;
import com.yuexun.beilunpatient.widget.ToastDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2019/4/18 0018.
 */

public class Act_Satisfaction_New extends BaseKJActivity implements IAreaHospView,ITemplateView,
        ISatisfactionDtlView,ICreateSatisfactionView {
    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.tv_title)
    EditText tvTitle;
    @Bind(R.id.tv_zone)
    TextView tvZone;
    @Bind(R.id.unit_tv)
    TextView unitTv;
    @Bind(R.id.type_tv)
    TextView typeTv;
    @Bind(R.id.mould_tv)
    TextView mouldTv;
    @Bind(R.id.originator_tv)
    TextView originatorTv;
    @Bind(R.id.answer_tv)
    TextView answerTv;
    @Bind(R.id.sex_tv)
    TextView sexTv;
    @Bind(R.id.tel_tv)
    TextView telTv;
    @Bind(R.id.card_tv)
    TextView cardTv;
    @Bind(R.id.health_tv)
    TextView healthTv;
    @Bind(R.id.topic_list)
    LinearLayoutForListView topicLayout;

    AreaHospPresenter areaHospPresenter;
    TemplatePresenter templatePresenter;
    SatisfactionDtlPresenter dtlPresenter;
    ICreateSatisfactionPresenter iCreateSatisfactionPresenter;

    //区域单位列表
    List<AreaHospBean> areaHospBeans = new ArrayList<>();
    //模板类型列表
    ArrayList<TemplateTypeBean> templateTypeBeans = new ArrayList<>();
    //模板列表
    ArrayList<TemplateBean> templateBeans = new ArrayList<>();

    private String hospId="",templateTypeId="",templateId="",templateName="";
    //题目列表
    private List<SatisfactionDtlBean.DtlListBean> topicList = new ArrayList<>();
    //已选题目列表
    private List<SatisfactionAnswerDtlBean.ListBeanX> answerList = new ArrayList<>();
    private SatisfactionTopicAdapter adapter;

    ToastDialog toastDialog;

    private List<UpdateSatisfactionBean> updateAnswer = new ArrayList<>();

    @Override
    public void setRootView() {
        setContentView(R.layout.act_satisfaction_new);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        toastDialog = new ToastDialog(this, "请稍后...");
        toastDialog.setCanceledOnTouchOutside(false);
        areaHospPresenter = new AreaHospPresenter(new AreaHospModel(), this);
        templatePresenter = new TemplatePresenter(new SatisfactionModel(),this);
        dtlPresenter = new SatisfactionDtlPresenter(new SatisfactionModel(), this);
        iCreateSatisfactionPresenter = new CreateSatisfactionPresenter(new SatisfactionModel(),this);
        setContent();
        ApiGetAreaHosp();
        ApiGetTemplateTypeData();
    }

    private void setContent() {
        answerTv.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.USER_NAME));
        sexTv.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SEX));
        telTv.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.TEL));
        cardTv.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.ID_CARD));
        healthTv.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.HEALTHID));
    }

    //获取医院单位列表
    private void ApiGetAreaHosp() {
        Map<String, String> params = new HashMap<>();
        areaHospPresenter.inquireAreaWithHospList(params);
    }

    //模板类型列表
    private void ApiGetTemplateTypeData() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        templatePresenter.inquireSatisfactionTemplateTypeList(params);
    }

    //模板类型列表
    private void ApiGetTemplateData() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("hospId", hospId);
        params.put("typeId", templateTypeId);
        templatePresenter.inquireSatisfactionTemplateList(params);
    }

    //请求题目详情
    private void ApiGetExamDtl() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("templateId", templateId + "");
        dtlPresenter.getSatisfactionDtl(params);
    }

    //提交调查结果
    private void ApiSubmitData(String dtlJson) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("satisfactionName", tvTitle.getText().toString());
        params.put("templateId", templateId);
        params.put("templateTitle", templateName);
        params.put("typeId", templateTypeId);
        params.put("hospId", hospId);
        params.put("answerStatus", "1");
        params.put("dtlJson", dtlJson);
        iCreateSatisfactionPresenter.createSatisfactionByUser(params);
    }


    @OnClick({R.id.title_back, R.id.ib_right, R.id.unit_ll, R.id.type_ll, R.id.mould_ll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.ib_right:
                if (tvTitle.getText().toString().isEmpty()) {
                    new ToastDialog(aty, "请输入满意度调查主题").show();
                } else if(unitTv.getText().toString().isEmpty()){
                    new ToastDialog(aty, "请选择单位").show();
                } else if(typeTv.getText().toString().isEmpty()){
                    new ToastDialog(aty, "请选择模板类型").show();
                }else if(mouldTv.getText().toString().isEmpty()){
                    new ToastDialog(aty, "请选择模板").show();
                }
                else {
                    toastDialog.show();
                    if (TextUtils.isEmpty(getAllAnswer(true))) {
                        ViewInject.toast("有未选择的题目");
                        toastDialog.dismiss();
                    } else {
                        ApiSubmitData(getAllAnswer(true));
                    }
                }
                break;
            case R.id.unit_ll:
                showAreaTypeDialog();
                break;
            case R.id.type_ll:
                showTemplateTypeDialog();
                break;
            case R.id.mould_ll:
                if (unitTv.getText().toString().isEmpty()) {
                    new ToastDialog(aty, "请先选择单位").show();
                } else if(typeTv.getText().toString().isEmpty()){
                    new ToastDialog(aty, "请先选择模板类型").show();
                }
                else {
                    ApiGetTemplateData();
                }
                break;
        }
    }

    private void showAreaTypeDialog() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true);

        for (int i = 0; i < areaHospBeans.size(); i++) {
            final int final1 = i;
            actionSheetDialog.addSheetItem(areaHospBeans.get(i).getHospitalName(), ActionSheetDialog.SheetItemColor.Blue,
                    new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            unitTv.setText(areaHospBeans.get(final1).getHospitalName());
                            hospId = areaHospBeans.get(final1).getId()+"";
                        }
                    });
        }
        actionSheetDialog.show();
        ;
    }

    private void showTemplateTypeDialog() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true);

        for (int i = 0; i < templateTypeBeans.size(); i++) {
            final int final1 = i;
            actionSheetDialog.addSheetItem(templateTypeBeans.get(i).getTypeName(), ActionSheetDialog.SheetItemColor.Blue,
                    new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            typeTv.setText(templateTypeBeans.get(final1).getTypeName());
                            templateTypeId = templateTypeBeans.get(final1).getTemplateTypeId()+"";
                        }
                    });
        }
        actionSheetDialog.show();
        ;
    }

    private void showTemplateDialog() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true);

        for (int i = 0; i < templateBeans.size(); i++) {
            final int final1 = i;
            actionSheetDialog.addSheetItem(templateBeans.get(i).getTitle(), ActionSheetDialog.SheetItemColor.Blue,
                    new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            mouldTv.setText(templateBeans.get(final1).getTitle());
                            originatorTv.setText(templateBeans.get(final1).getCreateName());
                            templateId = templateBeans.get(final1).getSatisfactionTemplateId()+"";
                            templateName = templateBeans.get(final1).getCreateName()+"";
                            ApiGetExamDtl();
                        }
                    });
        }
        actionSheetDialog.show();
        ;
    }


    //提取全部答案
    private String getAllAnswer(boolean isAllSelect) {
        updateAnswer.clear();

        final int childcount = topicLayout.getChildCount();
        for (int i = 0; i < childcount; i++) {
            View view = topicLayout.getChildAt(i);
            LinearLayout checkboxGroup = (LinearLayout) view.findViewById(R.id.checkbox_group);
            EditText other = (EditText) view.findViewById(R.id.et_other);

            UpdateSatisfactionBean item = new UpdateSatisfactionBean();
            item.setDtlId(topicList.get(i).getDtlId() + "");

            if (topicList.get(i).getShowType().equals("1") || topicList.get(i).getShowType().equals("3")) {    //单选 / 复选
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    CheckBox checkbox = (CheckBox) checkboxGroup.getChildAt(x);
                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);
                    } else {
                        noSelect++;
                        item_1.setDtlAnswer(-1);
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("2") || topicList.get(i).getShowType().equals("4")) { //单选+其他 / 复选其他
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    CheckBox checkbox = (CheckBox) checkboxGroup.getChildAt(x);
                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);
                    } else {
                        item_1.setDtlAnswer(-1);
                    }
                    if (x == (child_1 - 1) && checkbox.getText().toString().equals("其他") && checkbox.isChecked()) {
                        item_1.setDtlValue(other.getText().toString().trim());
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("5")) {         //文本框
                int child_1 = 1;
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();

                for (int x = 0; x < child_1; x++) {
                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    item_1.setDtlValue(other.getText().toString().trim());
                    listItem.add(item_1);
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("6") || topicList.get(i).getShowType().equals("8")) {//单选+二级单选  多选+二级单选
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    View view1 = checkboxGroup.getChildAt(x);
                    CheckBox checkbox = (CheckBox) view1.findViewById(R.id.checkbox);
                    FlowRadioGroup viewGroup = (FlowRadioGroup) view1.findViewById(R.id.viewGroup);

                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);

                        final int child_2 = viewGroup.getChildCount();
                        List<UpdateSatisfactionBean.ListBean> listItem2 = new ArrayList<>();
                        for (int y = 0; y < child_2; y++) {
                            RadioButton childAt = (RadioButton) viewGroup.getChildAt(y);
                            UpdateSatisfactionBean.ListBean item_2 = new UpdateSatisfactionBean.ListBean();
                            item_2.setDtlId(topicList.get(i).getList().get(x).getList().get(y).getDtlId() + "");
                            if (childAt.isChecked()) {
                                item_2.setDtlAnswer(1);
                            }else {
                                item_2.setDtlAnswer(-1);
                            }

                            listItem2.add(item_2);
                        }

                        item_1.setList(listItem2);
                    } else {
                        noSelect++;
                        item_1.setDtlAnswer(-1);
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("7") || topicList.get(i).getShowType().equals("9")) {//单选+二级多选 多选+二级多选
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    View view1 = checkboxGroup.getChildAt(x);
                    CheckBox checkbox = (CheckBox) view1.findViewById(R.id.checkbox);
                    FlowLayout viewGroup = (FlowLayout) view1.findViewById(R.id.viewGroup);

                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);

                        final int child_2 = viewGroup.getChildCount();
                        List<UpdateSatisfactionBean.ListBean> listItem2 = new ArrayList<>();
                        for (int y = 0; y < child_2; y++) {
                            CheckBox childAt = (CheckBox) viewGroup.getChildAt(y);
                            UpdateSatisfactionBean.ListBean item_2 = new UpdateSatisfactionBean.ListBean();
                            item_2.setDtlId(topicList.get(i).getList().get(x).getList().get(y).getDtlId() + "");
                            if (childAt.isChecked()) {
                                item_2.setDtlAnswer(1);
                            }else {
                                item_2.setDtlAnswer(-1);
                            }

                            listItem2.add(item_2);
                        }

                        item_1.setList(listItem2);
                    } else {
                        noSelect++;
                        item_1.setDtlAnswer(-1);
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            }
            updateAnswer.add(item);
        }
        return JSON.toJSONString(updateAnswer);
    }

    @Override
    public void getAreaWithHospList(BaseEntity<AreaBean> baseEntity) {
        if(baseEntity.getStatus().equals("200"))
        {
            areaHospBeans = baseEntity.getDatas().get(0).getHospList();
        }
        else {
            ViewInject.toast("获取单位列表失败"+baseEntity.getMessage());
        }
    }

    @Override
    public void inquireSatisfactionTemplateTypeList(BaseEntity<TemplateTypeBean> bean) {
        if(bean.getStatus().equals("200"))
        {
            templateTypeBeans = bean.getDatas();
        }
        else {
            ViewInject.toast("获取模板类型失败"+bean.getMessage());
        }
    }

    @Override
    public void inquireSatisfactionTemplateList(BaseEntity<TemplateBean> bean) {
        if(bean.getStatus().equals("200"))
        {
            if(templateBeans.size()>0)
            {
                templateBeans.clear();
            }
            templateBeans = bean.getDatas();
            showTemplateDialog();
        }
        else {
            ViewInject.toast("获取模板失败"+bean.getMessage());
        }
    }

    @Override
    public void getSatisfactionDtl(BaseEntity<SatisfactionDtlBean> bean) {
        if (bean.getStatus().equals("200")) {
            topicList = bean.getDatas().get(0).getDtlList();
            adapter = new SatisfactionTopicAdapter(this, topicList, true, answerList);
            topicLayout.setAdapter(adapter);
        } else {
            ViewInject.toast("获取题目详情错误");
        }
    }

    @Override
    public void getSatisfactionAnswerDtl(BaseEntity<SatisfactionAnswerDtlBean> bean) {

    }

    @Override
    public void createSatisfactionByUser(BaseEntity<String> bean) {
        if ("200".equals(bean.getStatus())) {
            ViewInject.toast("提交成功");
            finish();
        } else {
            ViewInject.toast("提交失败");
        }
        toastDialog.dismiss();
    }
}
